package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class QuanziApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";
    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";
    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private VideoApi videoApi;
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo=new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(page);

        Pageable pageable= PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("data")));
        Query query=new Query().with(pageable);
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if(CollUtil.isEmpty(timeLines)){
            return pageInfo;
        }
        //List<Object> publishIds = CollUtil.getFieldValues(timeLines, "publishId");
        List<Object> publishIds=new ArrayList<>();
        timeLines.forEach(timeLine -> publishIds.add(timeLine.getPublishId()));

        Query query1=Query.query(Criteria.where("id").in(publishIds))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishes = this.mongoTemplate.find(query1, Publish.class);
        if (CollUtil.isEmpty(publishes)){
            return pageInfo;
        }
        pageInfo.setRecords(publishes);
        return pageInfo;
    }


    @Override
    public String savePublish(Publish publish) {
        //对publish对象校验
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            //发布失败
            return null;
        }
        publish.setId(ObjectId.get());
        //自增长pid
        try {
            publish.setUserId(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());
            //写入到publish表中
            this.mongoTemplate.save(publish);
            //存入相册表
            Album album=new Album();
            album.setCreated(System.currentTimeMillis());
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());
            this.mongoTemplate.save(album,"quanzi_album_"+publish.getUserId());
            //存入时间表,异步完成
            this.timeLineService.saveTimeLine(publish.getUserId(),publish.getId());
        } catch (Exception e) {
            //TODO 需要做事务的回滚，Mongodb的单节点服务，不支持事务，对于回滚我们暂时不实现了
            log.error("发布动态失败~ publish = " + publish, e);
        }
        return publish.getId().toHexString();
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo=new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        //查询推荐结果
        String key="QUANZI_PUBLISH_RECOMMEND_"+userId;
        String s = this.redisTemplate.opsForValue().get(key);

//        int total=0;
        if (StrUtil.isEmpty(s)){
            return pageInfo;
        }
        List<Long> pidLongList = new ArrayList<>();
        String[] pids = StrUtil.split(s, ",");
        int[] ints = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex=ints[0];
        int endIndex=Math.min(ints[1],pids.length);
        for (int i = startIndex; i <endIndex ; i++) {
            pidLongList.add(Long.valueOf(pids[i]));
        }
//        total=pids.length;

        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
           /* int totalPage = PageUtil.totalPage(total, pageSize);
            Pageable pageable=PageRequest.of(page-totalPage-1,pageSize,Sort.by(Sort.Order.desc("created")));
            Query query=new Query().with(pageable);
            List<Publish> publishes = this.mongoTemplate.find(query, Publish.class);
            pageInfo.setRecords(publishes);
            return pageInfo;*/
        }
        Query query=Query.query(Criteria.where("pid").in(pidLongList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> records = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(records)) {
            //没有查询到数据
            return pageInfo;
        }
        pageInfo.setRecords(records);

        return pageInfo;
    }
    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id),Publish.class);
    }

    //点赞
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //查询用户是否已经点赞
        if(this.queryUserIsLike(userId,publishId)){
            //已点赞,直接退出
            return false;
        }
        //未点赞将数据传入comment表
        boolean data=this.saveComment(userId,publishId,CommentType.LIKE,null);
        if(!data){
            return false;
        }
        //将数据保存到Redis中
        //修改点赞数
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LIKE.toString();
        /*Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isEmpty(o)){
            //没有记录走数据库
            Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                    .and("commentType").is(CommentType.LIKE.getType()));
            long count = this.mongoTemplate.count(query, Comment.class);
            //最后将查到的数量存入Redis方便下次命中
            this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        }*/
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,1);
        //添加成已喜欢
        String userHashKey=this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    /**
     * 够着单个用户已点赞的记录key
     * @param userId
     * @return
     */
    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX+userId;
    }

    /**
     * 获取点赞的Rediskey
     * @param publishId
     * @return
     */
    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX+publishId;
    }

    /**
     * comment
     * @param userId 用户的id
     * @param publishId 发布文章的动态id
     * @param commentType 区别是喜欢评论还是点赞
     * @param content 内容
     * @return
     */
    private boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            Comment comment=new Comment();
            comment.setCreated(System.currentTimeMillis());
            comment.setCommentType(commentType.getType());
            comment.setContent(content);
            comment.setId(ObjectId.get());
            comment.setPublishId(new ObjectId(publishId));
            comment.setUserId(userId);

            Publish publish = this.queryPublishById(publishId);

            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if(ObjectUtil.isNotEmpty(myComment)){
                    comment.setPublishUserId(myComment.getUserId());
                }else{
                    Video video=this.videoApi.queryVideoById(publishId);
                    if(ObjectUtil.isNotEmpty(video)){
                        comment.setPublishUserId(video.getUserId());
                    }
                }
            }
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }

        return false;
    }

    private Comment queryCommentById(String publishId) {
        return this.mongoTemplate.findById(new ObjectId(publishId),Comment.class);
    }

    //取消点赞
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断用户时候已点赞(若是点了就取消,没电就返回false)
        if(!this.queryUserIsLike(userId, publishId)){
            //未点赞 无法取消
            return false;
        }
        //已点赞,删除MongoDB中的数据
        boolean data=this.deleteComment(userId,publishId,CommentType.LIKE);
        if(!data){
            //删除失败
            return false;
        }
        //将Redis中的点赞数减一,并将改用户的喜欢状态取消
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,-1);
        //取消喜欢
        String userHashKey=this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().delete(redisKey,userHashKey);
        return true;
    }

    /**
     * 删除一条comment记录
     * @param userId
     * @param publishId
     * @param like
     * @return
     */
    private boolean deleteComment(Long userId, String publishId, CommentType like) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(like.getType())
        );
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;

    }

    //点赞数
    @Override
    public Long queryLikeCount(String publishId) {
        //优先在Redis中命中  没有再走数据库
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LIKE.toString();
        Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(o)){
            //有数量直接返回
            return Convert.toLong(o);
        }
        //没有记录走数据库
        long count = queryCommentCount(publishId, CommentType.LIKE);
        //最后将查到的数量存入Redis方便下次命中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;
    }

    //是否点赞
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //优先在Redis中命中  没有再走数据库
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=this.getCommentUserLikeRedisKeyPrefix(userId);
        Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(o)){
            //有数量直接返回
            if(o.toString().equals("1")){
                return true;
            }
        }
        //没有记录走数据库
        Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("userId").is(userId).and("commentType").is(CommentType.LIKE.getType()));
        Long count= this.mongoTemplate.count(query, Comment.class);
        if (count==0){
            return false;
        }
        //最后将查到的数量存入Redis方便下次命中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,"1");

        return true;
    }

    //喜欢
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //是否喜欢
        Boolean result = this.queryUserIsLove(userId, publishId);
        if(result){
            //已经喜欢,没法添加
            return false;
        }
        //将喜欢的数据添加到容器中
        boolean b = this.saveComment(userId, publishId, CommentType.LOVE, null);
        if(!b){
            return false;
        }
        //将喜欢数和是否喜欢添加到redis中
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LOVE.toString();
        /*Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isEmpty(o)){
            //没有记录走数据库
            Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                    .and("commentType").is(CommentType.LOVE.getType()));
            long count = this.mongoTemplate.count(query, Comment.class);
            //最后将查到的数量存入Redis方便下次命中
            this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        }*/
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,1);//喜欢数+1

        String userHashKey=this.getCommentUserLoveRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    /**
     * 返回喜欢redisKey
     * @param userId
     * @return
     */
    private String getCommentUserLoveRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX+userId;
    }

    //取消喜欢
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {   //是否喜欢
        Boolean result = this.queryUserIsLove(userId, publishId);
        if(!result){
            //没有喜欢没法取消
            return false;
        }
        //将喜欢的数据数据删除
        boolean b = this.deleteComment(userId, publishId, CommentType.LOVE);
        if(!b){
            return false;
        }
        //将喜欢数和是否喜欢添加到redis中
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LOVE.toString();
        this.redisTemplate.opsForHash().increment(redisKey,hashKey,-1);//喜欢数+1

        String userHashKey=this.getCommentUserLoveRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;


    }

    //喜欢的数量
    @Override
    public Long queryLoveCount(String publishId) {
        //优先在Redis中命中  没有再走数据库
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=CommentType.LOVE.toString();
        Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(o)){
            //有数量直接返回
            return Convert.toLong(o);
        }
        //没有记录走数据库
        long count = queryCommentCount(publishId, CommentType.LOVE);
        //最后将查到的数量存入Redis方便下次命中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;

    }

    //是否喜欢
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //优先在Redis中命中  没有再走数据库
        String redisKey=this.getCommentRedisKeyPrefix(publishId);
        String hashKey=this.getCommentUserLoveRedisKeyPrefix(userId);
        Object o = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(o)){
            //有数量直接返回
            if(o.toString().equals("1")){
                return true;
            }
        }
        //没有记录走数据库
        Query query=Query.query(Criteria.where("publish").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE.getType()));
        Long count= this.mongoTemplate.count(query, Comment.class);
        if (count==0){
            return false;
        }
        //最后将查到的数量存入Redis方便下次命中
        this.redisTemplate.opsForHash().put(redisKey,hashKey,"1");

        return true;
    }

    //查询评论
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageInfo<Comment> pageInfo=new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        Pageable pageable=PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.asc("created")));
        Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
        .and("commentType").is(CommentType.COMMENT.getType())).with(pageable);
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
        if (CollUtil.isEmpty(comments)){
            //查询的comments为空
            return  pageInfo;
        }

        pageInfo.setRecords(comments);
        return pageInfo;
    }

    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {

        return this.saveComment(userId,publishId,CommentType.COMMENT,content);
    }
    //评论数量
    @Override
    public Long queryCommentCount(String publishId) {

        //没有记录走数据库
        long count = queryCommentCount(publishId, CommentType.COMMENT);
        return count;
    }

    private long queryCommentCount(String publishId, CommentType comment) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(comment.getType()));
        return this.mongoTemplate.count(query, Comment.class);
    }


    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,page,pageSize,CommentType.LIKE);
    }

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,page,pageSize,CommentType.LOVE);
    }

    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,page,pageSize,CommentType.COMMENT);
    }


    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize,CommentType commentType){
        PageInfo<Comment> pageInfo=new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        Pageable pageable =PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc("created")));

        Query query=Query.query(Criteria.where("publishUserId").is(userId)
        .and("commentType").is(commentType.getType())).with(pageable);
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);
        if (CollUtil.isEmpty(comments)){
            return pageInfo;
        }
        pageInfo.setRecords(comments);
        return  pageInfo;
    }

    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1 , pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);

        //查询自己的相册表
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        if(CollUtil.isEmpty(albumList)){
            return pageInfo;
        }

        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");

        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));

        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }
}
